/*
 * launcher.cpp
 *
 *  Created on: Oct 30, 2013
 *      Author: m
 */

#include <iostream>
#include <cstdlib>
#include "DefinicionesComunes.h"
#include "NewMessageQueue.h"
#include "NewSemaphore.h"
#include "NewSharedMemory.h"
#include "Sequence.h"
#include "CPrinter.h"
#include "ProcessAux.h"

#define ARG_NLESCTORES  1
#define ARG_NESCRITORES 2

using namespace ipc;

int main( int argc, char* argv[] )
{
    int nLectores;
    int nEscritores;
    int valorDolar = 10;     // Valor inicial del dolar

    CPrinter::setHeader( "launcher" );

    /*
     * Parseo los argumentos
     *
     * argv[1] Cantidad de lectores
     * argv[2] Cantidad de escritores
     */

    if ( argc != 3 )
    {
        CPrinter::printErr("ERROR: Cantidad de Argumentos Invalida.\n"
            "USO:\tlauncher [nLectores] [nEscritores]");
        exit(1);
    }

    std::stringstream ss;

    ss.str( argv[ARG_NLESCTORES] );
    ss >> nLectores;
    ss.clear();

    ss.str( argv[ARG_NESCRITORES] );
    ss >> nEscritores;
    ss.clear();

    // Construyo e inicializo los IPCs:
    SharedMemory<int>::create( IPC_BASE_FILE, SHM_CONT_LCON, 1 ).initialize(
            0 );
    SharedMemory<int>::create( IPC_BASE_FILE, SHM_CONT_LECT, 1 ).initialize(
            0 );
    SharedMemory<float>::create( IPC_BASE_FILE, SHM_BOARD, 1 ).initialize(
            valorDolar );
    Semaphore::create( IPC_BASE_FILE, SEM_ENTRADA , 1 ).initialize( 1 );
    Semaphore::create( IPC_BASE_FILE, SEM_CONT_LECT, 1 ).initialize( 1 );
    Semaphore::create( IPC_BASE_FILE, SEM_ESCRITOR , 1 ).initialize( 1 );
    Sequence::create( IPC_BASE_FILE, SEQ_ID_LECTOR );
    Sequence::create( IPC_BASE_FILE, SEQ_ID_ESCRIT );

    Semaphore semInicio =
            Semaphore::create( IPC_BASE_FILE, SEM_INICIO , 1 ).initialize( 0 );

    // Lanzo los distintos procesos

    std::string lectorPath    = "./lector";
    std::string escritorPath  = "./escritor";

    /**/
    CPrinter::printOut( "Lanzando Lectores.." );
    ProcessAux::launchProcess2( lectorPath, nLectores );

    CPrinter::printOut( "Lanzando Escritores.." );
    ProcessAux::launchProcess2( escritorPath, nEscritores );
    /**/

    for ( int i = 0; i < ( nLectores + nEscritores ); i++ )
    {
        semInicio.v();
    }

    return 0;
}
